/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package com.example.hello;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Vector;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;


import org.apache.cordova.*;

public class HelloWorld extends CordovaActivity implements LocationListener
{
	public static int NOT_REACHABLE = 0;
    public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1;
    public static int REACHABLE_VIA_WIFI_NETWORK = 2;

    public static final String WIFI = "wifi";
    public static final String WIMAX = "wimax";
    // mobile
    public static final String MOBILE = "mobile";
    // 2G network types
    public static final String GSM = "gsm";
    public static final String GPRS = "gprs";
    public static final String EDGE = "edge";
    // 3G network types
    public static final String CDMA = "cdma";
    public static final String UMTS = "umts";
    public static final String HSPA = "hspa";
    public static final String HSUPA = "hsupa";
    public static final String HSDPA = "hsdpa";
    public static final String ONEXRTT = "1xrtt";
    public static final String EHRPD = "ehrpd";
    // 4G network types
    public static final String LTE = "lte";
    public static final String UMB = "umb";
    public static final String HSPA_PLUS = "hspa+";
    // return type
    public static final String TYPE_UNKNOWN = "unknown";
    public static final String TYPE_ETHERNET = "ethernet";
    public static final String TYPE_WIFI = "wifi";
    public static final String TYPE_2G = "2g";
    public static final String TYPE_3G = "3g";
    public static final String TYPE_4G = "4g";
    public static final String TYPE_NONE = "none";
    CordovaInterface cordova;
    protected LocationManager lm;
    String latitude = "-34.918054"; 
    String longitude = "-56.166913";
    String parametros = "";
	    
	private String getConnectionInfo(NetworkInfo info) {
        String type = TYPE_NONE;
        if (info != null) {
            // If we are not connected to any network set type to none
            if (!info.isConnected()) {
                type = TYPE_NONE;
            }
            else {
                type = getType(info);
            }
        }
        Log.d("CordovaNetworkManager", "Connection Type: " + type);
        return type;
    }
	
	private String getType(NetworkInfo info) {
        if (info != null) {
            String type = info.getTypeName();

            if (type.toLowerCase().equals(WIFI)) {
                return TYPE_WIFI;
            }
            else if (type.toLowerCase().equals(MOBILE)) {
                type = info.getSubtypeName();
                if (type.toLowerCase().equals(GSM) ||
                        type.toLowerCase().equals(GPRS) ||
                        type.toLowerCase().equals(EDGE)) {
                    return TYPE_2G;
                }
                else if (type.toLowerCase().startsWith(CDMA) ||
                        type.toLowerCase().equals(UMTS) ||
                        type.toLowerCase().equals(ONEXRTT) ||
                        type.toLowerCase().equals(EHRPD) ||
                        type.toLowerCase().equals(HSUPA) ||
                        type.toLowerCase().equals(HSDPA) ||
                        type.toLowerCase().equals(HSPA)) {
                    return TYPE_3G;
                }
                else if (type.toLowerCase().equals(LTE) ||
                        type.toLowerCase().equals(UMB) ||
                        type.toLowerCase().equals(HSPA_PLUS)) {
                    return TYPE_4G;
                }
            }
        }
        else {
            return TYPE_NONE;
        }
        return TYPE_UNKNOWN;
    }
	
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
    	BaseDeDatos bd = new BaseDeDatos(this.getApplicationContext());
    	Vector<Establecimiento> supermercados = bd.listaSupermercados();
    	if (supermercados.size() == 0){
    		bd.cargaBase(this.getApplicationContext());
    		supermercados = bd.listaSupermercados();
    	}
    	System.out.println("Cantidad de lineas: " + supermercados.size());
    	Establecimiento auxEst;
		
    	for (int i = 0; i < supermercados.size(); i++){
    		auxEst = supermercados.get(i);
    		//System.out.println("Indice: " + i);
    		parametros = parametros + Integer.toString(i) + "=";
    		//System.out.println("Est: " + auxEst.nombreComercial + "," + auxEst.sucursal + "," + auxEst.latitud + "," + auxEst.longitud);
    		parametros = parametros + auxEst.nombreComercial + "|" + auxEst.latitud + "|" + auxEst.longitud + "|" + Integer.toString(i) + "|" + auxEst.sucursal + "&";
    	}
    	parametros = parametros.substring(0, parametros.length()-1);
    // TODO: Armar lista para pasar
    	
    	final TelephonyManager tm =(TelephonyManager)getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
        super.onCreate(savedInstanceState);
        super.init();
        // Set by <content src="index.html" /> in config.xml
        //super.loadUrl(Config.getStartUrl());
        ConnectivityManager sockMan = (ConnectivityManager) getBaseContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = sockMan.getActiveNetworkInfo();
        
        Context context = getBaseContext(); 
        //LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        Criteria cri = new Criteria();
        cri.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = lm.getBestProvider(cri, true);
        System.out.println("Provedor: "+provider);
        Location loc = getLastKnownLocation();
        
        if (loc != null){
	        Double d1 = loc.getLatitude();
	        Double d2 = loc.getLongitude();
	        latitude = Location.convert(d1,Location.FORMAT_DEGREES);
	        longitude = Location.convert(d2,Location.FORMAT_DEGREES);
	        latitude = latitude.replace(',', '.');
	        longitude = longitude.replace(',', '.');
	        System.out.println("LATLONG: " + latitude + longitude);
        } else {
        	System.out.println("PosicionNULL");
        }
        super.loadUrl("file:///android_asset/www/index.html?"+parametros+"&coordenadas="+latitude+"|"+longitude, 3000);
       // super.loadUrl("file:///android_asset/www/hola.html", 3000);

        
    }
    
    private Location getLastKnownLocation() {
    	LocationManager mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
        List<String> providers = mLocationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            Location l = mLocationManager.getLastKnownLocation(provider);
            if (l == null) {
                continue;
            }
            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                // Found best last known location: %s", l);
                bestLocation = l;
            }
        }
        return bestLocation;
    }
    
    @Override
    public void onLocationChanged(Location location) {
    
    	latitude = Location.convert(location.getLatitude(), Location.FORMAT_DEGREES);
    	longitude = Location.convert(location.getLongitude(), Location.FORMAT_DEGREES);
    	
    }
    
    @Override
    public void onProviderDisabled(String provider) {
    Log.d("Latitude","disable");
    }

    @Override
    public void onProviderEnabled(String provider) {
    Log.d("Latitude","enable");
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    Log.d("Latitude","status");
    }
}

